package com.mayn.jst.erp.action;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.Db;
import com.mayn.jst.login.TaobaoLoginAction;
import com.mayn.jst.shop.action.ShopAccountAction;
import com.mayn.util.DateUtil;
import com.mayn.util.FetchUtils;
import com.mayn.util.SendCloudMailUtil;
import com.mayn.util.StringUtil;

import net.sf.json.JSONArray;
/**
 * 生意参谋抓取类
 * @author 梁志渊
 * @version 
 * 版本号：【100-000-000】<br/>
 * 创建日期：:2017年7月4日 <br/>
 * 历史修订：<br/>
 */
public class SycmAction {
	
	private static final Logger LOG = LoggerFactory.getLogger(SycmAction.class);
	
	/**
	 * 生意参谋数据抓取测试
	 */
	public static void TestSycm(Date currTime){
		int shopId = 5;//设置店铺ID
		//初始化map
		List<Map<String, Object>> ListMap = null;
//		String date = DateUtil.dateFmtToString(currTime,"yyyy-MM-dd");
		String date = "2017-09-01";
		//开始时间
		String id = null;
		JSONArray jsonArray = null;
		
//		JfinalInit.InitDb(false, null);	
		
		try {
			//检查cookie
			if(TaobaoLoginAction.checkAndSaveTaobaoLoginCookie(shopId)){
			String cookie = ShopAccountAction.getShopAccountCookie(shopId);
			String token = TaobaoLoginAction.getSycmToken(cookie);
			//LOG.info("token:" + token);
			
			jsonArray  = TaobaoLoginAction.getHotProducts(cookie, token, date, date);
			
			 //LOG.info("jsonArray"+jsonArray.toString());
			 //jsonArray 传 map中去
			 ListMap = FetchUtils.InsertToMap(jsonArray);
						//插入数据
			 		for (int j = 0; j < ListMap.size(); j++) {
			 			Map<String, Object> map =new HashMap<String,Object>();
			 			map = ListMap.get(j);
			 			//打印数据
			 			for (String key : map.keySet()) {
			 			   //LOG.info("key= "+ key + " and value= " + map.get(key));
			 			   //判断数据字段
			 			   if(key.equals("itemId")){
			 				   id = map.get(key).toString();
			 			   }
			 			  }
			 			 
			 			//判断数据库是否有数据
			 			if(checkSHPData(date,id) == true){
			 				//检查原有数据
			 				LOG.info("date:",date);
			 				LOG.info("今天数据已采集!");
			 				continue;
			 			}else {
			 			//save操作
						if(FetchUtils.savedata_sycm(map,shopId,date) != true) {
							LOG.info("插入失败！");
							return;
						}else {
							LOG.info("插入成功！");
						}
			 		}
			 	}//end for
			}else{
					LOG.info("指定店铺cookie不生效！");
					String mailText = "生意参谋--获取店铺cookie失败！"+"\r\n";
				    SendCloudMailUtil.sendMailCode(mailText,"service@mayn.com.cn");
				}
		} catch (Exception e) {
				e.printStackTrace();
			}
		}
	

	/**
	 * 检查生意参谋表是否有数据
	 * @author Administrator
	 * @return false:无 true:有
	 */
	private static boolean checkSHPData(String date,String id) {
		
		String sql = "SELECT COUNT(*) from shop_hot_product where  shop_hot_product.SHP_DATE = ? AND shop_hot_product.SHP_ITEMID = ?;";
		int c = Db.use("erp").queryLong(sql,date,id).intValue();
		if (c >= 1) {
			return true;
		}
		return false;
		
	}
	
	/**
	 * 保存生意参谋数据
	 * @para
	 * @author 梁志渊
	 * @return 
	 */
	public static boolean savedata_sycm(Map<String, Object>  map,int shopId,String date) {
		
		try {

			int orderNum = 0;//排名ID
			Date shpDate = DateUtil.stringFmtToDate(date,"yyyy-MM-dd");//suf抓取时间
			
			double payOrdCnt =0.0; 
			double payByrRateIndex =0.0;
			double tradeIndexCrc =0.0;
			double  pvIndex =0.0;
			double searchIndex =0.0;
		    boolean mallItem ;
		    String   itemPicUrl = "";
		    double itemPrice =0.0;
		    String shopName = "";
		    String itemUrl =""; 
		    String itemId = "";
		    String shopUrl = "";
		    String sameGoodUrl  = "";
		    String itemTitle = ""; 
			
			Date shpCreateDatetime =DateUtil.dateToTimestamp(new Date()  ) ;//创建时间
			int 	shpCreateBy = 1;//创建人
			Date shpModifyDatetime = DateUtil.dateToTimestamp(new Date()) ;//修改时间
			int    shpModifyBy	= 1;//修改人
			int    shpDel = 0;		 //未删除
			
			if( StringUtil.isBlank(map.get("orderNum"))){
				orderNum = 0;
			}else{
				orderNum = (int) map.get("orderNum");
			}
			if( StringUtil.isBlank(map.get("payOrdCnt"))){
				payOrdCnt = 0.0;
			}else {
				payOrdCnt = (double) map.get("payOrdCnt");
			}
			
			if( StringUtil.isBlank(map.get("payByrRateIndex"))){
				LOG.info("空值!------>payByrRateIndex");
			}else {
				payByrRateIndex = (double) map.get("payByrRateIndex");
			}
			
			if( StringUtil.isBlank(map.get("tradeIndexCrc"))){
				LOG.info("空值!------>tradeIndexCrc");
			}else{
				tradeIndexCrc = (double) map.get("tradeIndexCrc");
			}
			if( StringUtil.isBlank(map.get("pvIndex"))){
				LOG.info("空值!------>pvIndex");
			}else{
				pvIndex = (double) map.get("pvIndex");
			}
			if( StringUtil.isBlank(map.get("searchIndex"))){
				LOG.info("空值!------>searchIndex");
			}else{
				searchIndex = (double) map.get("searchIndex");
			}
			if( StringUtil.isBlank(map.get("mallItem"))){
				LOG.info("空值!------>mallItem");
				mallItem = false;
			}else{
				mallItem = (boolean) map.get("mallItem");
			}
			
		    if(StringUtil.isBlank(itemPicUrl)){
		    	itemPicUrl = "";
		    }else{
		    	itemPicUrl =  map.get("itemPicUrl").toString();
		    }
		    
		    if(StringUtil.isBlank(itemPrice)){
		    	itemPrice = 0.0;
		    }else{
		    	itemPrice = (double) map.get("itemPrice");
		    }
		    
			if(StringUtil.isBlank(map.get("shopName"))){
				shopName = "";
			}else {
				shopName = map.get("shopName").toString();
			}
			
			if(StringUtil.isBlank(map.get("itemUrl"))){
				itemUrl = "";
			}else {
				itemUrl =   map.get("itemUrl").toString();
			}
			
			if(StringUtil.isBlank(map.get("itemId"))){
				itemId = "";
			}else {
				itemId = map.get("itemId").toString();
			}
			
			if(StringUtil.isBlank(map.get("shopUrl"))){
				shopUrl = "";
			}else {
				shopUrl= map.get("shopUrl").toString();
			}
			
			if(StringUtil.isBlank(map.get("sameGoodUrl"))){
				sameGoodUrl = "";
			}else {
				sameGoodUrl= map.get("sameGoodUrl").toString();
			}
			
			if(StringUtil.isBlank(map.get("itemTitle"))){
				itemTitle = "";
			}else {
				itemTitle= map.get("itemTitle").toString();
			}
			
	 
			String sql = "INSERT INTO `db-mayn-erp-prd`.`shop_hot_product` ( "
					+ "`SHP_DATE`,"
					+ "`SHP_SHOP_ID`,"
					+ "`SHP_ORDERNUM`, "
					+ "`SHP_PAYORDCNT`, "
					+ "`SHP_PAYBYRRATEINDEX`,"
					+ " `SHP_TRADEINDEXCRC`, "
					+ "`SHP_PVINDEX`, "
					+ "`SHP_SEARCHINDEX`,"
					+ " `SHP_MALLITEM`,"
					+ " `SHP_ITEMPICURL`, "
					+ "`SHP_ITEMPRICE`, "
					+ "`SHP_SHOPNAME`,"
					+ " `SHP_ITEMURL`,"
					+ " `SHP_ITEMID`, "
					+ "`SHP_SHOPURL`, "
					+ "`SHP_SAMEGOODURL`, "
					+ "`SHP_ITEMTITLE`,"
					+"`SHP_CREATE_DATETIME`,"
					+"`SHP_CREATE_BY`,"
					+"`SHP_MODIFY_DATETIME`,"
					+"`SHP_MODIFY_BY`,"
					+ "`SHP_DEL`)"
					
					+ " VALUES  ('" +  shpDate
					+"','" + shopId
					+"','" + orderNum
					+"','" + payOrdCnt
					+ "','"+ payByrRateIndex
					+ "','"+ tradeIndexCrc
					+ "','"+ pvIndex
					+ "','"+ searchIndex
					
					+ "','"+ mallItem
					
					+ "','"+ itemPicUrl
					+ "','"+ itemPrice
					+ "','"+ shopName
					+ "','"+ itemUrl
					+ "','"+ itemId
					+ "','"+ shopUrl
					+ "','"+ sameGoodUrl
					+ "','"+ itemTitle
					+ "','"+ shpCreateDatetime
					+ "','"+ shpCreateBy
					+ "','"+ shpModifyDatetime
					+ "','"+ shpModifyBy
					+ "','"+ shpDel
					+ "');";
			
			 //LOG.info("保存数据的ID --->:orderNum:"+orderNum);
			 //LOG.info("保存数据的时间--->"+shpDate);
			 //LOG.info("保存数据的 payOrdCnt--->"+payOrdCnt);
			if( Db.use("erp").update(sql) > 0){				
				LOG.info("update-->插入成功！");
				return true;
			}else {
				LOG.info("插入失败！");
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}
